package com.jshan.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jshan.base.entity.SysUser;
import com.jshan.mapper.SysUserMapper;
import com.jshan.service.SysUserDeptService;
import com.jshan.service.SysUserService;
import com.jshan.base.vo.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import cn.hutool.crypto.digest.BCrypt;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    private final SysUserMapper userMapper;

    @Autowired
    private SysUserDeptService userDeptService;

    @Value("${file.upload.path}")
    private String uploadBasePath;

    @Override
    public Result login(SysUser loginUser) {
        // 1. 查询用户
        SysUser user = userMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, loginUser.getUsername()));

        if (user == null || !BCrypt.checkpw(loginUser.getPassword(), user.getPassword())) {
            return Result.fail(500, "用户名或密码错误");
        }
        // 2. 使用 Sa-Token 进行登录
        StpUtil.login(user.getId());

        // 3. 获取 token
        String token = StpUtil.getTokenValue();

        // 4. 返回用户信息和 token
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        user.setPassword(null); // 清除敏感信息
        data.put("user", user);

        return Result.ok(data);
    }

    // public static void main(String[] args) {
    // System.out.println(BCrypt.hashpw("123456", BCrypt.gensalt()));
    // System.out.println(BCrypt.checkpw("123456",
    // "$2a$10$arjy7JKoNwFO.YJwAHiMNeyAr71rtaAUlYxGzwsUamOHIMxP71xbe"));
    // }
    @Override
    public Result getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        SysUser user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在");
        }
        // 清除敏感信息
        user.setPassword(null);
        return Result.ok(user);
    }

    @Override
    public List<SysUser> listAll() {
        return list();
    }

    @Override
    public IPage<SysUser> getUserPage(IPage<SysUser> page) {
        return page(page, null);
    }

    @Override
    public boolean saveUser(SysUser user) {
        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        user.setRealName(user.getNickname());
        return save(user);
    }

    @Override
    public boolean updateUser(SysUser user) {
        // If password is provided, encode it before updating
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        }
        return updateById(user);
    }

    @Override
    public boolean deleteUser(Long id) {
        return removeById(id);
    }

    @Override
    public boolean updateProfile(SysUser user) {
        // 只允许更新昵称、手机号、邮箱
        SysUser existingUser = getById(user.getId());
        if (existingUser == null) {
            return false;
        }
        existingUser.setNickname(user.getNickname()); // 将 realName 改为 nickname
        existingUser.setPhone(user.getPhone());
        existingUser.setEmail(user.getEmail());
        return updateById(existingUser);
    }

    @Override
    public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
        SysUser user = getById(userId);
        if (user == null || !BCrypt.checkpw(oldPassword, user.getPassword())) {
            return false; // 旧密码不正确或用户不存在
        }
        user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt()));
        return updateById(user);
    }

    @Override
    public String uploadAvatar(Long userId, MultipartFile file) {
        SysUser user = getById(userId);
        if (user == null) {
            return null;
        }

        // 构建日期目录，例如 20250616
        String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 完整的上传目录：D:/data/ops/avatar/20250616
        String fullUploadDir = uploadBasePath + File.separator + "avatar" + File.separator + dateDir;

        File uploadDirFile = new File(fullUploadDir);
        if (!uploadDirFile.exists()) {
            uploadDirFile.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        String filePath = fullUploadDir + File.separator + fileName;

        try {
            file.transferTo(new File(filePath));
            // 更新用户头像路径为相对路径，例如 /uploads/avatar/20250616/xxx.jpg
            String relativePath = "/uploads/avatar/" + dateDir + "/" + fileName;
            user.setAvatar(relativePath);
            updateById(user);
            return relativePath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public IPage<SysUser> getUsersByDeptId(IPage<SysUser> page, Long deptId, String username, String phone,
            Integer status) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();

        // 如果 deptId 不为空且不为 0，则根据部门 ID 筛选用户
        if (deptId != null && deptId != 0) {
            // 通过 exists 子查询来关联用户和部门
            queryWrapper.apply(
                    "EXISTS (SELECT 1 FROM sys_user_dept sud WHERE sud.user_id = sys_user.id AND sud.dept_id = {0})",
                    deptId);
        }

        // 根据用户名模糊查询
        if (username != null && !username.isEmpty()) {
            queryWrapper.like(SysUser::getUsername, username);
        }
        // 根据手机号模糊查询
        if (phone != null && !phone.isEmpty()) {
            queryWrapper.like(SysUser::getPhone, phone);
        }
        // 根据状态精确匹配
        if (status != null) {
            queryWrapper.eq(SysUser::getStatus, status);
        }

        return page(page, queryWrapper);
    }
}
